package com.xmhmyh.generalframework.common.aliyunOss.service.impl;

import cn.hutool.core.io.FileUtil;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClient;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.common.auth.DefaultCredentialProvider;
import com.aliyun.oss.common.utils.BinaryUtil;
import com.aliyun.oss.model.MatchMode;
import com.aliyun.oss.model.PolicyConditions;
import com.xmhmyh.generalframework.common.aliyunOss.enums.UploadImgType;
import com.xmhmyh.generalframework.common.aliyunOss.service.IAliOssService;
import com.xmhmyh.generalframework.framework.config.AliOssConfig;
import com.xmhmyh.generalframework.framework.uid.UidGenerator;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.util.Arrays;
import java.util.Date;
import java.util.LinkedHashMap;
import java.util.Map;

/**
 * @Author: 于丁
 * @DateTime: 2019/12/24 2:21 下午
 */
@Service
public class AliOssServiceImpl implements IAliOssService {

    @Autowired
    UidGenerator uidGenerator;
    @Autowired
    AliOssConfig aliOssConfig;
    // todo 图片内容检测处理

    public static final String[] VIDEO_FILE_TYPES = {"mp4"};
    public static final String[] IMG_FILE_TYPES = {"png", "jpg", "jpeg", "bmp", "gif"};

    @Override
    public Map<String, String> getSign(String fileType) throws Exception {
        String accessId = aliOssConfig.getAccessId(); // 请填写您的AccessKeyId。
        String accessKey = aliOssConfig.getAccessKey(); // 请填写您的AccessKeySecret。
        String endpoint = aliOssConfig.getEndpoint(); // 请填写您的 endpoint。
        String bucket = aliOssConfig.getBucket(); // 请填写您的 bucketname 。
        String host = aliOssConfig.getHost(); // host的格式为 bucketname.endpoint
        // callbackUrl为 上传回调服务器的URL，请将下面的IP和Port配置为您自己的真实信息。
//        String callbackUrl = "http://88.88.88.88.:8888";
        String dir = "";
        if (Arrays.asList(VIDEO_FILE_TYPES).contains(fileType)) {
            dir = aliOssConfig.getVideoDir() + uidGenerator.getUID() + "." + fileType;
        } else if (Arrays.asList(IMG_FILE_TYPES).contains(fileType)) {
            dir = aliOssConfig.getDir() + uidGenerator.getUID() + "." + fileType;
        } else {
            throw new Exception("格式不允许");
        }
        OSSClient client = new OSSClient(endpoint, new DefaultCredentialProvider(accessId, accessKey), null);
        long expireTime = 30;
        long expireEndTime = System.currentTimeMillis() + expireTime * 1000;
        Date expiration = new Date(expireEndTime);
        PolicyConditions policyConds = new PolicyConditions();
        policyConds.addConditionItem(PolicyConditions.COND_CONTENT_LENGTH_RANGE, 0, 1048576000);
        policyConds.addConditionItem(MatchMode.StartWith, PolicyConditions.COND_KEY, dir);
        String postPolicy = client.generatePostPolicy(expiration, policyConds);
        byte[] binaryData = postPolicy.getBytes("utf-8");
        String encodedPolicy = BinaryUtil.toBase64String(binaryData);
        String postSignature = client.calculatePostSignature(postPolicy);

        Map<String, String> respMap = new LinkedHashMap<String, String>();
        respMap.put("accessid", accessId);
        respMap.put("policy", encodedPolicy);
        respMap.put("signature", postSignature);
        respMap.put("dir", dir);
        respMap.put("host", host);
        respMap.put("expire", String.valueOf(expireEndTime / 1000));
        return respMap;
    }

    @Override
    public String uploadFile(InputStream inputStream, UploadImgType uploadImgType){
        String accessId = aliOssConfig.getAccessId(); // 请填写您的AccessKeyId。
        String accessKey = aliOssConfig.getAccessKey(); // 请填写您的AccessKeySecret。
        String endpoint = aliOssConfig.getEndpoint(); // 请填写您的 endpoint。
        String bucket = aliOssConfig.getBucket(); // 请填写您的 bucketname 。
        String host = aliOssConfig.getHost(); // host的格式为 bucketname.endpoint
        // 创建OSSClient实例。
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessId, accessKey);
        // 上传文件。
        String filePath = aliOssConfig.getDir() + uidGenerator.getUID() + "." + uploadImgType.getLabel();
        ossClient.putObject(bucket, filePath, inputStream);

        // 关闭OSSClient。
        ossClient.shutdown();
        return filePath;
    }

    @Override
    public String getPath(byte[] bytes, UploadImgType uploadImgType){
        String path = uploadFile(new ByteArrayInputStream(bytes), uploadImgType);
        return path;
    }
}

